//
//  DDExchangeInfoWrite.m
//  dingdang
//
//  Created by lichq on 7/24/15.
//  Copyright (c) 2015 阮 沧晖. All rights reserved.
//

#import "DDExchangeInfoWrite.h"
#import "UICommonFunc.h"
#import "DDExchangeSuccess.h"
#import "PlaceholderTextView.h"
#import "UIViewController+MJPopupViewController.h"
#import "DDNetWorkAPIClient.h"
#import "DDMGiftOrder.h"
#import "DDAddressVC.h"
#import "DDAddress.h"
#import "StringUtil.h"
#import "DDForgetPwdVC.h"

@interface DDExchangeInfoWrite (){
    DDMGiftOrderCell *cell;
    NSString *intgeral;
}

@property (weak, nonatomic) IBOutlet UITextField *tfPerson;
@property (weak, nonatomic) IBOutlet UITextField *tfPhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *tfAddress;
@property (weak, nonatomic) IBOutlet UITextField *tfAddressDetailed;
@property (weak, nonatomic) IBOutlet UILabel *labScore;
@property(weak, nonatomic) IBOutlet PlaceholderTextView *textView_body;

@property (nonatomic,strong)DDAddressCell *addressModel;
@end

@implementation DDExchangeInfoWrite

- (void)viewWillAppear:(BOOL)animated
{
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
//    [network queryGitfOrder:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
//        NSLog(@"%@",dict);
//        NSError *error ;
//        DDMGiftOrder *log = [[DDMGiftOrder alloc] initWithDictionary:dict error:&error];
//        if (error) {
//            NSLog(@"%@",error.userInfo);
//        }
//        
//        cell = log.list[0];
//        
//        self.tfPerson.text = cell.consignee;
//        self.tfPhoneNum.text = cell.phone;
//        self.tfAddress.text = cell.address;
//    }];
    [network queryIntegral:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        NSLog(@"%@",dict);
        if (isSuccess) {
            intgeral = [[dict objectForKey:@"integral"]stringValue];
            self.labScore.text = intgeral;
        }
    }];
    
    if (_addressModel) {
        self.tfPerson.text = _addressModel.consignee;
        self.tfPhoneNum.text = _addressModel.phoneNumber;
        self.tfAddress.text = _addressModel.district;
        self.tfAddressDetailed.text = _addressModel.address;
        cell = [[DDMGiftOrderCell alloc] init];
        cell.consignee = _addressModel.consignee;
        cell.areaName = _addressModel.district;
        cell.address = _addressModel.address;
        cell.phone = _addressModel.phoneNumber;
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    
    self.textView_body.layer.cornerRadius = 10;
    self.textView_body.layer.masksToBounds = YES;
    self.textView_body.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.textView_body.layer.borderWidth = .5;
    self.textView_body.placeholderColor = [UIColor lightGrayColor];
    self.textView_body.placeholder = @"您还有什么交代的，请在此处说明";
    
    DDSharedUser *user = [DDSharedUser shared];
    self.addressModel = [user getExchangeInfo];
}

- (void)createUI
{
    self.view.backgroundColor = RGB(245, 245, 245);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(@"积分兑换", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

//确认兑换
- (IBAction)exchange:(id)sender{
    if ([StringUtil isEmptyString:cell.consignee] || [StringUtil isEmptyString:cell.address] || [StringUtil isEmptyString:cell.phone]) {
        [UICommonFunc showAlert:@"请填写相关信息！"];
        return;
    }
    
    DDSharedUser *user = [DDSharedUser shared];
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
    [network getUserInfo:user.access_token completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        DDSharedUser *sharedUser = [DDSharedUser shared];
        BOOL hasPayPassword = ![sharedUser.userInfo.hasPayPassword isEqualToString:@"0"];
        if (isSuccess) {
            hasPayPassword = [[dict objectForKey:@"hasPayPassword"] boolValue];
            sharedUser.userInfo.hasPayPassword = [dict objectForKey:@"hasPayPassword"];
        }
        
        if (!hasPayPassword) {// 没有支付密码 需要设置支付密码
            DDForgetPwdVC *fogetPwd = [[DDForgetPwdVC alloc] initWithNibName:@"DDForgetPwdVC" bundle:nil];
            [self.navigationController pushViewController:fogetPwd animated:YES];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入支付密码" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles :@"确认", @"忘记密码", nil];
            alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
            UITextField * txt = [[UITextField alloc] init];
            txt.backgroundColor = [UIColor whiteColor];
            txt.frame = CGRectMake(alert.center.x+65,alert.center.y+48, 150,23);
            [alert addSubview:txt];
            [alert show];
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
        {
            UITextField *tf=[alertView textFieldAtIndex:0];
            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
            
            NSDictionary *dictionary = @{@"giftId": _gift.id,
                                         //                                 @"exchangeNum": cell.exchangeNum,
                                         //                                 @"payPassword": cell.payPassword,
                                         @"exchangeNum": @"1", //不知道哪里可以选择兑换数量，默认一个 待补充-jiangxp
                                         @"payPassword": tf.text,
                                         @"consignee": cell.consignee,
                                         @"areaName": cell.areaName,
                                         @"address": cell.address,
                                         @"zipCode": cell.zipCode == nil?@"" : cell.zipCode,
                                         @"phone": cell.phone};
            [network gitExchange:dictionary completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                if (isSuccess) {
                    NSLog(@"兑换成功");
                    DDSharedUser *user = [DDSharedUser shared];
                    [user saveExchangeInfo:cell];
                    self.addressModel = [user getExchangeInfo];
                    DDExchangeSuccess *vc = [[DDExchangeSuccess alloc]initWithNibName:@"DDExchangeSuccess" bundle:nil];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    [UICommonFunc showAlert:message];
                }
            }];
        }
            break;
        case 2:
        {
            DDForgetPwdVC *fogetPwd = [[DDForgetPwdVC alloc] initWithNibName:@"DDForgetPwdVC" bundle:nil];
            
            [self.navigationController pushViewController:fogetPwd animated:YES];
        }
            break;
        default:
            break;
    }
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self.textView_body resignFirstResponder];
    }
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    [self.textView_body resignFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.textView_body resignFirstResponder];
    [self.tfPerson resignFirstResponder];
    [self.tfPhoneNum resignFirstResponder];
    [self.tfAddress resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)selectAddress:(id)sender {
    
    __weak DDExchangeInfoWrite *weakSelf = self;
    DDAddressVC *addressInfo = [[DDAddressVC alloc] initWithNibName:@"DDAddressVC" bundle:nil];
    addressInfo.source = @"exchange";
    addressInfo.addressResult = ^(DDAddressCell *add)
    {
       weakSelf.addressModel = add;
        
    };
    [self.navigationController pushViewController:addressInfo animated:YES];
}
@end
